package com.wswy.wyjk.ui.practiceNew;

import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomSheetDialog;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.PagerSnapHelper;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.my.httpapi.api.annotation.ViewL;
import com.my.httpapi.api.baseView.BaseActivity;
import com.tencent.mmkv.MMKV;
import com.wswy.wyjk.AppContext;
import com.wswy.wyjk.R;
import com.wswy.wyjk.api.Api;
import com.wswy.wyjk.api.MMKVConstant;

import com.wswy.wyjk.api.entity.RequestParameter;
import com.wswy.wyjk.core.App;
import com.wswy.wyjk.model.PracticeData;
import com.wswy.wyjk.model.PracticeType;
import com.wswy.wyjk.model.vo.ExamRegularConfig;
import com.wswy.wyjk.ui.practice.dialog.ExamRegularHintDialog;
import com.wswy.wyjk.ui.practiceNew.Adapter.TIMUChooseAdapter;
import com.wswy.wyjk.ui.practiceNew.Dialog.CustomDialog;
import com.wswy.wyjk.ui.practiceNew.event.ExamEvent;
import com.wswy.wyjk.ui.practiceNew.Adapter.ExamAdapter;
import com.wswy.wyjk.ui.uitls.PracticeTypeUtils;
import com.wswy.wyjk.utils.Tools;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@ViewL(R.layout.activity_exam)
public class ExamActivity extends BaseActivity {

    private TextView tvCountdownTime;
    private TextView tvOrderIndex;
    private RecyclerView recyclerView;
    private ImageView imgBack;
    private TextView tvImmedSubmit, tvRightCount, tvWrongCount;
    private ExamAdapter examAdapter;
    private List<PracticeData> practiceList;
    private int localPosition = 0;
    private PagerSnapHelper pagerSnapHelper;
    private LinearLayoutManager mLinearLayoutManager;
    private int rightCount = 0, WrongCount = 0;
    private long millisUntilFinish;
    public static List<PracticeData> practiceErrList = new ArrayList<>();
    private TIMUChooseAdapter timuChooseAdapter;
    private BottomSheetDialog dialog;
    private TextView tvCurrPosition, tvDialogRightCount, tvDialogWrongCount;
    private int fraction;
    private int correctNum = 1;

    @Override
    protected void initData(Bundle savedInstanceState) {
        initView();
        initData();
        initListener();
    }

    @Override
    protected String showTitle() {
        return null;
    }

    @Override
    protected boolean statusBarIsBlack() {
        return true;
    }

    @Override
    protected void destroy() {
        EventBus.getDefault().unregister(this);
        if(timer!=null){
            timer.cancel();
            timer=null;
        }
    }

    @Override
    public void onBackPressed() {
        exitDialog();
    }

    private void initView() {
        recyclerView = findViewById(R.id.recyclerView);
        tvCountdownTime = findViewById(R.id.tv_countdown_time);
        tvOrderIndex = findViewById(R.id.tv_order_index);
        tvImmedSubmit = findViewById(R.id.tv_immed_submit);
        tvRightCount = findViewById(R.id.tv_right_count);
        tvWrongCount = findViewById(R.id.tv_wrong_count);
        imgBack = findViewById(R.id.img_back);
    }

    private void initData() {
        EventBus.getDefault().register(this);
        correctNum = MMKV.defaultMMKV().decodeInt(MMKVConstant.ERRCOUNT, 1);
        mLinearLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);
        examAdapter = new ExamAdapter();
        recyclerView.setLayoutManager(mLinearLayoutManager);
        recyclerView.setAdapter(examAdapter);
        practiceList = App.getDaoSession().findAllPractice(PracticeTypeUtils.getPracticeType(PracticeType.TYPE_EXAM));
        examAdapter.setNewData(practiceList);
        pagerSnapHelper = new PagerSnapHelper();
        pagerSnapHelper.attachToRecyclerView(recyclerView);
        tvOrderIndex.setText((localPosition + 1) + "/" + practiceList.size());
        initFraction();
        showExamRegularDialog();
        imgBack.setOnClickListener(view -> exitDialog());
        initBottomSheetDialog();
    }

    private void initListener() {
        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                localPosition = recyclerView.getChildAdapterPosition(pagerSnapHelper.findSnapView(mLinearLayoutManager));
                tvOrderIndex.setText((localPosition + 1) + "/" + practiceList.size());
                tvCurrPosition.setText((localPosition + 1) + "/" + practiceList.size());
            }
        });

        tvImmedSubmit.setOnClickListener(view -> {
            new CustomDialog.Builder(ExamActivity.this).setTitle("还有" + (practiceList.size() - rightCount - WrongCount) + "道题没做，确定交卷？")
                    .setPositiveButton((dialog, which) -> {
                        commit();
                    }).create().show();
        });

        tvOrderIndex.setOnClickListener(view -> {
            if (dialog != null) {
                dialog.show();
            }
        });
    }

    private void exitDialog(){
        new CustomDialog.Builder(ExamActivity.this).setTitle("还有" + (practiceList.size() - rightCount - WrongCount) + "道题没做，确定退出？")
                .setPositiveButton((dialog, which) -> finish()).create().show();
    }

    private void commit() {
        String token = MMKV.defaultMMKV().decodeString(MMKVConstant.TOKEN);
        if (!TextUtils.isEmpty(token)) {
            record(45 * 60 * 1000 - millisUntilFinish);
            return;
        }
        gotoResult();
    }

    private void gotoResult() {
        for (int i = 0; i < practiceList.size(); i++) {
            if (practiceList.get(i).getDoIt() == 2) {
                practiceErrList.add(practiceList.get(i));
            }
        }
        Intent intent = new Intent(ExamActivity.this, ExamResultActivity.class);
        intent.putExtra("time", (45 * 60 * 1000 - millisUntilFinish));
        intent.putExtra("right", rightCount);
        intent.putExtra("wrong", WrongCount);
        intent.putExtra("count", practiceList.size());
        startActivity(intent);
        finish();
    }

    private void initFraction() {
        if (practiceList.size() == 100) {
            fraction = 1;
        } else {
            fraction = 2;
        }
    }

    private void initBottomSheetDialog() {
        dialog = new BottomSheetDialog(this, R.style.BottomSheetDialog);
        View dialogView = LayoutInflater.from(this)
                .inflate(R.layout.layout_dialog_choose_timu, null);
        RecyclerView rv_1 = dialogView.findViewById(R.id.rv_1);
        GridLayoutManager mLinearLayoutManager1 = new GridLayoutManager(this, 6, GridLayoutManager.VERTICAL, false);
        timuChooseAdapter = new TIMUChooseAdapter();
        rv_1.setLayoutManager(mLinearLayoutManager1);
        rv_1.setAdapter(timuChooseAdapter);
        timuChooseAdapter.setNewData(practiceList);
        tvCurrPosition = dialogView.findViewById(R.id.tv_curr_position);
        tvDialogRightCount = dialogView.findViewById(R.id.tv_dialog_right_count);
        tvDialogWrongCount = dialogView.findViewById(R.id.tv_dialog_wrong_count);
        tvCurrPosition.setText((localPosition + 1) + "/" + practiceList.size());
        timuChooseAdapter.setOnItemClickListener((adapter, view, position) -> {
            recyclerView.scrollToPosition(position);
            localPosition = position;
            tvOrderIndex.setText((localPosition + 1) + "/" + practiceList.size());
            tvCurrPosition.setText((localPosition + 1) + "/" + practiceList.size());
            dialog.dismiss();
        });
        dialog.setContentView(dialogView);
    }

    private void showExamRegularDialog() {
        ExamRegularConfig examRegularConfig = new ExamRegularConfig(PracticeTypeUtils.getPracticeType().licenseType, PracticeTypeUtils.getPracticeType().subjectType
                , 45, 90, fraction, fraction, fraction,
                AppContext.getContext().getString(R.string.exam_regular_hint1, 45, fraction, 90));
        ExamRegularHintDialog examRegularHintDialog = new ExamRegularHintDialog(ExamActivity.this, examRegularConfig);
        examRegularHintDialog.setOnDismissListener(dialogInterface -> {
            timer.start();
        });
        examRegularHintDialog.show();
    }


    private CountDownTimer timer = new CountDownTimer(45 * 60 * 1000, 1000) {
        public void onTick(long millisUntilFinished) {
            millisUntilFinish = millisUntilFinished;
            tvCountdownTime.setText(Tools.formatSecondTime(millisUntilFinished / 1000));
        }

        public void onFinish() {
            commit();
        }
    };

    private void record(long time) {
        PracticeType practiceType = PracticeTypeUtils.getPracticeType();
        Map<String, String> map = new HashMap<>();
        map.put("carType", practiceType.licenseType.getTypeName());
        map.put("course", practiceType.subjectType.getTypeName() + "");
        map.put("score", (rightCount * fraction) + "");
        map.put("duration", (time / 1000) + "");
        map.put("areaCode", practiceType.areaCode);
        subscribe(Api.getApi().record(RequestParameter.generate().getSingedParams(map)),
                request(data -> gotoResult(), err -> gotoResult(), true));
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void examEvent(ExamEvent examEvent) {
        if (examEvent.isRight()) {
            recyclerView.smoothScrollToPosition(++localPosition);
            tvRightCount.setText(++rightCount + "");
            tvDialogRightCount.setText(tvRightCount.getText().toString());
        } else {
            tvWrongCount.setText(++WrongCount + "");
            tvDialogWrongCount.setText(tvWrongCount.getText().toString());
        }
        timuChooseAdapter.notifyDataSetChanged();
        //上传题目
        uplaodTitle(examEvent.getId(), examEvent.isRight());
    }

    private void uplaodTitle(int id, boolean isRight) {
        String token = MMKV.defaultMMKV().decodeString(MMKVConstant.TOKEN);
        if (TextUtils.isEmpty(token)) {
            return;
        }
        Map<String, String> map = new HashMap<>();
        map.put("qid", id + "");
        map.put("correctNum", correctNum + "");
        if (isRight) {
            map.put("result", "1");
        } else {
            map.put("result", "0");
        }
        subscribe(Api.getApi().uploadErr(RequestParameter.generate().getSingedParams(map)),
                request(data -> {

                }, false));
    }
}
